import json
import os  

def save_to_file(pets, filename="data/pets.json"):
    """
    Saves pet data to a JSON file.

    Args:
        pets (list): List of pet dictionaries to be saved.
        filename (str, optional): Path to the JSON file. Defaults to "data/pets.json".

    Returns:
        bool: True if save is successful, False otherwise.
    """
    try:
        if not filename:
            filename = "data/pets.json"
        
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(pets, f, ensure_ascii=False, indent=2)
        print(f"✅ save successfully to {filename}")
        return True
    except Exception as e: 
        print(f"❌ cannot save well: {str(e)}")
        return False

def load_from_file(filename="data/pets.json", force_reload=False):  
    """
    Loads pet data from a JSON file.

    Args:
        filename (str, optional): Path to the JSON file. Defaults to "data/pets.json".
        force_reload (bool, optional): Whether to reload the file even if it exists. Defaults to False.

    Returns:
        list: List of pet dictionaries loaded from the file.
    """
    try:
        if not filename:
            filename = "data/pets.json"
        
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        
        if not os.path.exists(filename):
            with open(filename, "w", encoding="utf-8") as f:
                json.dump([], f, ensure_ascii=False, indent=2)
            print(f"✅ creat {filename}")
        
        with open(filename, 'r', encoding='utf-8') as f:
            if force_reload:
                f.flush()
                f.seek(0)
            return json.load(f)
    except Exception as e:
        print(f"❌ cannot load file: {str(e)}")
        return []
